<template>
  <div>
    <!-- 闭店提醒弹窗 -->
    <el-dialog 
      v-model="showCloseReminderDialog" 
      title="门店闭店提醒" 
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :show-close="true"
      @close="onReminderDialogClose"
    >
      <div class="reminder-content">
        <el-alert
          title="有门店已闭店，请及时处理"
          type="warning"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;"
        />
        <el-table :data="closeReminders" style="width: 100%" max-height="400" border>
          <el-table-column prop="storeName" label="门店名称" min-width="150">
            <template #default="{ row }">{{ row.storeName || '-' }}</template>
          </el-table-column>
          <el-table-column prop="franchisee" label="加盟商" min-width="120">
            <template #default="{ row }">{{ row.franchisee || '-' }}</template>
          </el-table-column>
          <el-table-column prop="phone" label="联系电话" min-width="130">
            <template #default="{ row }">{{ row.phone || '-' }}</template>
          </el-table-column>
          <el-table-column prop="closeDate" label="闭店日期" min-width="120">
            <template #default="{ row }">{{ formatJoinDateOnly(row.closeDate) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                @click="markAsRead(row.storeId)"
                :loading="row.loading"
              >
                收到
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="reminder-footer">
          <el-button @click="onReminderDialogClose">关闭</el-button>
          <el-button type="primary" @click="markAllAsRead" :loading="markAllLoading">
            全部标记为已读
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-card>
      <el-button type="primary" @click="showForm = true" v-if="!showForm">新增加盟</el-button>
      <el-dialog v-model="showForm" title="用户数据收集" width="600px" @close="onDialogClose">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" style="max-width: 500px; margin: 0 auto;">
          <el-form-item label="加盟商" prop="franchisee">
            <el-input v-model="form.franchisee" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="开店省份" prop="province">
            <el-select v-model="form.province" placeholder="请选择省份">
              <el-option v-for="item in provinces" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" />
          </el-form-item>
          <el-form-item label="加盟日期" prop="joinDate">
            <el-date-picker 
              v-model="form.joinDate" 
              type="date" 
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="身份证号码" prop="idNumber">
            <el-input v-model="form.idNumber" />
          </el-form-item>
          <el-form-item label="微信群名" prop="wechatGroup">
            <el-input v-model="form.wechatGroup" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" :loading="submitLoading" :disabled="submitLoading">提交</el-button>
            <el-button @click="showForm = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>

    <el-card style="margin-top: 32px;">
      <h3>未交接列表</h3>
      <el-table :data="pagedPendingHandoverStores" style="width: 100%">
        <el-table-column prop="storeName" label="门店名称">
          <template #default="{ row }">{{ row.storeName || '-' }}</template>
        </el-table-column>
        <el-table-column prop="franchisee" label="加盟商">
          <template #default="{ row }">{{ row.franchisee || '-' }}</template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码">
          <template #default="{ row }">{{ row.phone || '-' }}</template>
        </el-table-column>
        <el-table-column prop="province" label="开店省份">
          <template #default="{ row }">{{ row.province || '-' }}</template>
        </el-table-column>
        <el-table-column prop="address" label="详细地址">
          <template #default="{ row }">{{ row.address || '-' }}</template>
        </el-table-column>
        <el-table-column prop="joinDate" label="加盟日期">
          <template #default="{ row }">{{ formatJoinDateOnly(row.joinDate) }}</template>
        </el-table-column>
        <el-table-column prop="idNumber" label="身份证号码">
          <template #default="{ row }">{{ row.idNumber || '-' }}</template>
        </el-table-column>
        <el-table-column prop="wechatGroup" label="微信群名">
          <template #default="{ row }">{{ row.wechatGroup || '-' }}</template>
        </el-table-column>
        <el-table-column label="下一个交接人">
          <template #default="{ row }">
            <el-select
              v-model="handoverSelections[row.storeId]"
              placeholder="请选择"
              style="width: 120px"
              filterable
            >
              <el-option
                v-for="item in employee0List"
                :key="item.employeeId"
                :label="item.name"
                :value="item.employeeId"
              />
            </el-select>
            <el-button
              type="primary"
              size="small"
              style="margin-left: 8px"
              @click="onHandoverSubmit(row.storeId)"
            >提交</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :current-page="pendingCurrentPage"
          :page-size="pendingPageSize"
          :total="pendingHandoverStores.length"
          @current-change="handlePendingPageChange"
        />
      </div>
    </el-card>

    <el-card style="margin-top: 32px;">
      <h3>已交接列表</h3>
      <el-table :data="pagedCompletedHandoverStores" style="width: 100%">
        <el-table-column prop="storeName" label="门店名称">
          <template #default="{ row }">{{ row.storeName || '-' }}</template>
        </el-table-column>
        <el-table-column prop="franchisee" label="加盟商">
          <template #default="{ row }">{{ row.franchisee || '-' }}</template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码">
          <template #default="{ row }">{{ row.phone || '-' }}</template>
        </el-table-column>
        <el-table-column prop="province" label="开店省份">
          <template #default="{ row }">{{ row.province || '-' }}</template>
        </el-table-column>
        <el-table-column prop="address" label="详细地址">
          <template #default="{ row }">{{ row.address || '-' }}</template>
        </el-table-column>
        <el-table-column prop="joinDate" label="加盟日期">
          <template #default="{ row }">{{ formatJoinDateOnly(row.joinDate) }}</template>
        </el-table-column>
        <el-table-column prop="idNumber" label="身份证号码">
          <template #default="{ row }">{{ row.idNumber || '-' }}</template>
        </el-table-column>
        <el-table-column prop="wechatGroup" label="微信群名">
          <template #default="{ row }">{{ row.wechatGroup || '-' }}</template>
        </el-table-column>
        <el-table-column label="下一个交接人">
          <template #default="{ row }">
            {{ getEmployeeNameById(row.userId) }}
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :current-page="completedCurrentPage"
          :page-size="completedPageSize"
          :total="completedHandoverStores.length"
          @current-change="handleCompletedPageChange"
        />
      </div>
    </el-card>

    <el-card style="margin-top: 32px;">
      <h3>已闭店门店列表</h3>
      <el-table :data="pagedClosedStores" style="width: 100%">
        <el-table-column prop="storeName" label="门店名称">
          <template #default="{ row }">{{ row.storeName || '-' }}</template>
        </el-table-column>
        <el-table-column prop="franchisee" label="加盟商">
          <template #default="{ row }">{{ row.franchisee || '-' }}</template>
        </el-table-column>
        <el-table-column prop="address" label="地址">
          <template #default="{ row }">{{ row.address || '-' }}</template>
        </el-table-column>
        <el-table-column prop="joinDate" label="加盟时间">
          <template #default="{ row }">{{ formatJoinDateOnly(row.joinDate) }}</template>
        </el-table-column>
        <el-table-column prop="closeDate" label="闭店时间">
          <template #default="{ row }">{{ formatJoinDateOnly(row.closeDate) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="showStoreDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :current-page="closedCurrentPage"
          :page-size="closedPageSize"
          :total="closedTotal"
          @current-change="handleClosedPageChange"
        />
      </div>
    </el-card>

    <!-- 门店详情弹窗 -->
    <el-dialog v-model="showDetailDialog" title="门店详情" width="600px">
      <div v-if="selectedStore" style="padding: 20px;">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="门店名称">{{ selectedStore.storeName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="门店地址">{{ selectedStore.storeAddress || '-' }}</el-descriptions-item>
          <el-descriptions-item label="提交人">{{ selectedStore.submitter || '-' }}</el-descriptions-item>
          <el-descriptions-item label="加盟商">{{ selectedStore.franchisee || '-' }}</el-descriptions-item>
          <el-descriptions-item label="加盟商电话">{{ selectedStore.franchiseePhone || '-' }}</el-descriptions-item>
          <!-- <el-descriptions-item label="美团门店ID">{{ selectedStore.meituanStoreId || '-' }}</el-descriptions-item> -->
          <!-- <el-descriptions-item label="饿了么门店ID">{{ selectedStore.elemeStoreId || '-' }}</el-descriptions-item> -->
          <el-descriptions-item label="门店所在1">{{ selectedStore.storeLocation1 || '-' }}</el-descriptions-item>
          <el-descriptions-item label="门店所在2">{{ selectedStore.storeLocation2 || '-' }}</el-descriptions-item>
          <el-descriptions-item label="京东账号">{{ selectedStore.jdAccount || '-' }}</el-descriptions-item>
          <!-- <el-descriptions-item label="京东门店ID">{{ selectedStore.jdStoreId || '-' }}</el-descriptions-item> -->
          <el-descriptions-item label="情况说明">{{ selectedStore.description || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ selectedStore.remarks || '-' }}</el-descriptions-item>
          <el-descriptions-item label="门店状态">{{ selectedStore.closeStore === 1 ? '开店中' : '已闭店' }}</el-descriptions-item>
          <el-descriptions-item label="神枪手">{{ selectedStore.sharpshooter === 1 ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item label="拼好饭">{{ selectedStore.pinghaofan === 1 ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item label="加盟日期">{{ formatJoinDateOnly(selectedStore.joinDate) }}</el-descriptions-item>
          <el-descriptions-item label="闭店时间">{{ formatJoinDateOnly(selectedStore.closeDate) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onActivated } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useUserStore } from '@/store/user';
import { useRouter } from 'vue-router';
import { formatDateTime } from '@/utils/dateUtils';

const userStore = useUserStore();
const router = useRouter();
const formRef = ref();
const form = ref({
  employee0Id: userStore.userId,
  franchisee: '',
  phone: '',
  province: '',
  address: '',
  joinDate: '',
  idNumber: '',
  wechatGroup: ''
});

const provinces = [
  '北京', '天津', '上海', '重庆', '河北', '山西', '辽宁', '吉林', '黑龙江',
  '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南',
  '广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海', '台湾',
  '内蒙古', '广西', '西藏', '宁夏', '新疆', '香港', '澳门'
];

const rules = {
  franchisee: [{ required: true, message: '请输入加盟商' }],
  phone: [
    { required: true, message: '请输入手机号码' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
  ],
  province: [{ required: true, message: '请选择省份' }],
  address: [{ required: true, message: '请输入详细地址' }],
  joinDate: [{ required: true, message: '请选择加盟日期' }],
  idNumber: [
    { pattern: /^(\d{15}|\d{17}[\dXx])$/, message: '请输入正确的身份证号码' }
  ],
  wechatGroup: [{ required: true, message: '请输入微信群名' }]
};

const submittedStores = ref([]);
const closedStores = ref([]); // 已闭店门店列表
const handoverFormRef = ref();
const handoverForm = ref({
  storeId: '',
  submitTo: ''
});
const handoverSelections = ref({});
const employee0List = ref([]);
const showForm = ref(false);
const showDetailDialog = ref(false); // 详情弹窗显示状态
const selectedStore = ref(null); // 选中的门店详情
const submitLoading = ref(false); // 新增：防止多次点击

// 闭店提醒相关
const showCloseReminderDialog = ref(false);
const closeReminders = ref([]);
const markAllLoading = ref(false);

function onDialogClose() {
  // 可选：重置表单内容
  // formRef.value?.resetFields();
}

const pendingHandoverStores = computed(() =>
  submittedStores.value.filter(item => Number(item.status) === -1)
);
const completedHandoverStores = computed(() => {
  const filtered = submittedStores.value.filter(item => item.userId);
  // 按加盟时间排序，时间越靠后的排在越前面
  return filtered.sort((a, b) => {
    const dateA = new Date(a.joinDate || 0);
    const dateB = new Date(b.joinDate || 0);
    return dateB - dateA; // 降序排列，最新的在前
  });
});

async function fetchSubmittedStores() {
  try {
    let res;
    if (Number(userStore.roleCode) === 3) {
      // 管理员
      res = await axios.get('http://121.43.176.9:8090/api/store/all');
    } else {
      res = await axios.get('http://121.43.176.9:8090/api/store/by-employee0', {
        params: { employee0Id: userStore.userId }
      });
    }
    if (res.data.code === 200) {
      submittedStores.value = res.data.data || [];
    } else {
      submittedStores.value = [];
    }
  } catch (e) {
    submittedStores.value = [];
  }
}

async function fetchClosedStores() {
  try {
    const queryData = { closeStore: 0 };
    // 发送分页参数
    const res = await axios.post(
      `http://121.43.176.9:8090/oldStore/search?userId=${userStore.userId}&page=${closedCurrentPage.value}&size=${closedPageSize}`,
      queryData
    );
    if (res.data && res.data.records) {
      const filtered = (res.data.records || []).filter(item => Number(item.closeStore) === 0);
      closedStores.value = filtered.map(item => ({
        ...item,
        address: item.storeAddress,
        closeDate: item.closeTime,
        joinDate: item.joinDate
      }));
      // 若后端未按条件统计 total，这里回退为本页过滤后的数量
      closedTotal.value = (typeof res.data.total === 'number' ? res.data.total : filtered.length) || filtered.length;
    } else {
      closedStores.value = [];
      closedTotal.value = 0;
    }
  } catch (e) {
    console.error('获取已闭店门店失败:', e);
    closedStores.value = [];
    closedTotal.value = 0;
  }
}

async function fetchEmployee0List() {
  try {
    const res = await axios.get('http://121.43.176.9:8090/api/employee/employee0-list');
    if (res.data.code === 200) {
      employee0List.value = res.data.data || [];
    } else {
      employee0List.value = [];
    }
  } catch (e) {
    employee0List.value = [];
  }
}

onMounted(() => {
  fetchSubmittedStores();
  fetchClosedStores();
  fetchEmployee0List();
  fetchCloseReminders(); // 获取闭店提醒
});

// 页面激活时也检查提醒
onActivated(() => {
  fetchCloseReminders();
});

function onSubmit() {
  if (submitLoading.value) return; // 防止多次点击
  formRef.value.validate().then(() => {
    submitLoading.value = true;
    axios.post('http://121.43.176.9:8090/api/store/addData', form.value).then(res => {
      submitLoading.value = false;
      if (res.data.code === 200) {
        ElMessage.success('提交成功');
        showForm.value = false; // 提交成功后关闭弹窗
        try {
          router.go(o);
        } catch (e) {}
        fetchSubmittedStores(); // 刷新已提交列表
        fetchClosedStores(); // 刷新已闭店列表
      } else {
        ElMessage.error(res.data.msg || '提交失败');
      }
    }).catch(() => {
      submitLoading.value = false;
      ElMessage.error('提交失败');
    });
  }).catch(() => {
    ElMessage.error('请完善表单信息');
  });
}

async function onHandoverSubmit(storeId) {
  const userId = handoverSelections.value[storeId];
  if (!userId) {
    ElMessage.warning('请选择下一个交接人');
    return;
  }
  const employee = employee0List.value.find(e => e.employeeId === userId);

  let stage;
  if (Number(userStore.roleCode) === -1) {
    stage = 1;
  }

  const log = {
    submitFrom: userStore.account,
    submitTo: employee.account,
    submitTime: new Date(),
    storeId,
    stage: stage.toString()
  };
  try {
    // 1. 新增流程日志
    const res = await axios.post('http://121.43.176.9:8090/api/log/add', log);
    if (res.data.code !== 200) {
      ElMessage.error(res.data.msg || '交接失败');
      return;
    }
    // 2. 更新门店状态
    const statusRes = await axios.post('http://121.43.176.9:8090/api/store/update-status0', null, { params: { storeId } });
    if (statusRes.data.code !== 200) {
      ElMessage.error(statusRes.data.msg || '门店状态更新失败');
      return;
    }
    // 3. 更新门店userId
    const userRes = await axios.post('http://121.43.176.9:8090/api/store/update-user', null, { params: { storeId, userId } });
    if (userRes.data.code === 200) {
      ElMessage.success('交接成功，门店状态和userId已更新');
      handoverSelections.value[storeId] = '';
      fetchSubmittedStores();
    } else {
      ElMessage.error(userRes.data.msg || 'userId更新失败');
    }
  } catch (e) {
    ElMessage.error('交接失败');
  }
}

function getEmployeeNameById(userId) {
  const emp = employee0List.value.find(e => e.employeeId === userId);
  return emp ? emp.name : userId || '-';
}

function formatJoinDate(date) {
  return formatDateTime(date);
}

function formatJoinDateOnly(date) {
  if (!date) return '-';
  const dateObj = new Date(date);
  if (isNaN(dateObj.getTime())) return '-';
  return dateObj.toISOString().split('T')[0]; // 只返回 YYYY-MM-DD 格式
}

// 分页相关
const pendingCurrentPage = ref(1)
const pendingPageSize = 5
const completedCurrentPage = ref(1)
const completedPageSize = 10
const closedCurrentPage = ref(1)
const closedPageSize = 15
const closedTotal = ref(0)

const pagedPendingHandoverStores = computed(() => {
  const start = (pendingCurrentPage.value - 1) * pendingPageSize
  return pendingHandoverStores.value.slice(start, start + pendingPageSize)
})
const pagedCompletedHandoverStores = computed(() => {
  const start = (completedCurrentPage.value - 1) * completedPageSize
  return completedHandoverStores.value.slice(start, start + completedPageSize)
})
const pagedClosedStores = computed(() => closedStores.value)

function handlePendingPageChange(page) {
  pendingCurrentPage.value = page
}
function handleCompletedPageChange(page) {
  completedCurrentPage.value = page
}
function handleClosedPageChange(page) {
  closedCurrentPage.value = page
  fetchClosedStores()
}

// 显示门店详情
function showStoreDetail(store) {
  selectedStore.value = store;
  showDetailDialog.value = true;
}

// 获取闭店提醒
async function fetchCloseReminders() {
  try {
    const res = await axios.get('http://121.43.176.9:8090/api/store-close-reminder/unread');
    
    if (res.data.code === 200) {
      closeReminders.value = res.data.data || [];
      // 如果有未读提醒，显示弹窗
      if (closeReminders.value.length > 0) {
        showCloseReminderDialog.value = true;
      }
    }
  } catch (error) {
    console.error('获取闭店提醒失败:', error);
  }
}

// 标记单个提醒为已读
async function markAsRead(storeId) {
  const reminder = closeReminders.value.find(r => r.storeId === storeId);
  if (reminder) {
    reminder.loading = true;
  }
  
  try {
    const res = await axios.post('http://121.43.176.9:8090/api/store-close-reminder/mark-read', null, {
      params: { storeId }
    });
    
    if (res.data.code === 200) {
      ElMessage.success('已标记为已读');
      // 从列表中移除已读的提醒
      closeReminders.value = closeReminders.value.filter(r => r.storeId !== storeId);
      
      // 如果没有更多提醒，关闭弹窗
      if (closeReminders.value.length === 0) {
        showCloseReminderDialog.value = false;
      }
    } else {
      ElMessage.error(res.data.msg || '标记失败');
    }
  } catch (error) {
    console.error('标记已读失败:', error);
    ElMessage.error('标记失败，请重试');
  } finally {
    if (reminder) {
      reminder.loading = false;
    }
  }
}

// 关闭提醒弹窗
function onReminderDialogClose() {
  showCloseReminderDialog.value = false;
}

// 批量标记所有提醒为已读
async function markAllAsRead() {
  if (closeReminders.value.length === 0) return;
  
  markAllLoading.value = true;
  try {
    const storeIds = closeReminders.value.map(r => r.storeId).join(',');
    const res = await axios.post('http://121.43.176.9:8090/api/store-close-reminder/batch-mark-read', null, {
      params: { storeIds }
    });
    
    if (res.data.code === 200) {
      ElMessage.success('已全部标记为已读');
      closeReminders.value = [];
      showCloseReminderDialog.value = false;
    } else {
      ElMessage.error(res.data.msg || '批量标记失败');
    }
  } catch (error) {
    console.error('批量标记失败:', error);
    ElMessage.error('批量标记失败，请重试');
  } finally {
    markAllLoading.value = false;
  }
}
</script>

<style scoped>
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0 4px;
}

.reminder-content {
  padding: 10px 0;
}

.reminder-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
  padding-top: 10px;
}

/* 确保弹窗内容完整显示 */
:deep(.el-dialog) {
  max-height: 90vh;
  overflow: hidden;
}

:deep(.el-dialog__body) {
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}
</style>